<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $row = (int)$_POST["row"];
    $col = (int)$_POST["col"];

    // 用户落子
    $_SESSION['board'][$row][$col] = 'X';

    // 检查用户是否获胜
    $winner = checkWinner($_SESSION['board']);
    if ($winner) {
        $response = [
            'winner' => $winner,
            'draw' => false,
            'computerMove' => null
        ];
    } else {
        // 检查是否平局
        if (isDraw($_SESSION['board'])) {
            $response = [
                'winner' => null,
                'draw' => true,
                'computerMove' => null
            ];
        } else {
            // 电脑落子
            $computerMove = makeComputerMove($_SESSION['board']);
            $_SESSION['board'][$computerMove[0]][$computerMove[1]] = 'O';

            // 检查电脑是否获胜
            $winner = checkWinner($_SESSION['board']);
            if ($winner) {
                $response = [
                    'winner' => $winner,
                    'draw' => false,
                    'computerMove' => $computerMove
                ];
            } else {
                // 检查是否平局
                if (isDraw($_SESSION['board'])) {
                    $response = [
                        'winner' => null,
                        'draw' => true,
                        'computerMove' => $computerMove
                    ];
                } else {
                    $response = [
                        'winner' => null,
                        'draw' => false,
                        'computerMove' => $computerMove
                    ];
                }
            }
        }
    }

    header('Content-Type: application/json');
    echo json_encode($response);
}

function checkWinner($board) {
    // 检查行
    for ($i = 0; $i < 3; $i++) {
        if ($board[$i][0] === $board[$i][1] && $board[$i][1] === $board[$i][2] && $board[$i][0] !== '') {
            return $board[$i][0];
        }
    }

    // 检查列
    for ($j = 0; $j < 3; $j++) {
        if ($board[0][$j] === $board[1][$j] && $board[1][$j] === $board[2][$j] && $board[0][$j] !== '') {
            return $board[0][$j];
        }
    }

    // 检查对角线
    if ($board[0][0] === $board[1][1] && $board[1][1] === $board[2][2] && $board[0][0] !== '') {
        return $board[0][0];
    }
    if ($board[0][2] === $board[1][1] && $board[1][1] === $board[2][0] && $board[0][2] !== '') {
        return $board[0][2];
    }

    return null;
}

function isDraw($board) {
    foreach ($board as $row) {
        foreach ($row as $cell) {
            if ($cell === '') {
                return false;
            }
        }
    }
    return true;
}

function makeComputerMove($board) {
    for ($i = 0; $i < 3; $i++) {
        for ($j = 0; $j < 3; $j++) {
            if ($board[$i][$j] === '') {
                return [$i, $j];
            }
        }
    }
    return null;
}
?>